<?php

/**
 * 微信支付
 * zc
 * 2018年11月7日15:15:16
 */
class WeixinPay_model extends MY_Model
{
    function __construct()
    {
       parent::__construct();
       $this->load->library('WeixinPay/WxPay.Data');
       $this->load->library('WeixinPay/WxPay.Api');
       $this->load->library('WeixinPay/WxPay.Api');
    }
    
    /**
     * 获取用户openid
     */
    function getOpenid()
    {
        if (isset($_COOKIE['userinfo']['openid']) && $_COOKIE['userinfo']['openid']!="") {
            $openid = $_COOKIE['userinfo']['openid'];
        } else {
            if (!isset($_GET['code'])){
                //触发微信返回code码
                $baseUrl = urlencode('http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'].$_SERVER['QUERY_STRING']);
                $url = $this->wechat->_CreateOauthUrlForCode($baseUrl);
                Header("Location: $url");
                exit();
            } else {
                //获取code码，以获取openid
                $code = $_GET['code'];
                $openid = $this->wechat->getOpenidFromMp($code);
                return $openid;
            }
        }
    }

    /**
     * 微信支付
     */
    function pay($post)
    {
        try{
            $tools = new JSAPiPay();
            
            $input = new WxPayUnifiedOrder();
            $input->SetBody("test");
            $input->SetAttach("test");
            $input->SetOut_trade_no("sdkphp".date("YmdHis"));
            $input->SetTotal_fee("1");
            $input->SetTime_start(date("YmdHis"));
            $input->SetTime_expire(date("YmdHis", time() + 600));
            $input->SetGoods_tag("test");
            $input->SetNotify_url(base_url().'Weixin/Pay/notify');
            $input->SetTrade_type("JSAPI");
            $input->SetOpenid($post['openid']);
            $config = new WxPayConfig();
            $order = WxPayApi::unifiedOrder($config, $input);
            
            $jsApiParameters = $tools->GetJsApiParameters($order);
        
            //获取共享收货地址js函数参数
            $editAddress = $tools->GetEditAddressParameters();
        } catch(Exception $e) {
            // log
            exit;
        }

        return array('jsApiParameters'=>$jsApiParameters, 'editAddress'=>$editAddress);
    }

}